import hashlib
import re
from time import localtime, time

import requests
from bs4 import BeautifulSoup

from checkin import CheckIn

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.87 Safari/537.36"
}


class Aoj(CheckIn):
    name = "AOJ"

    def __init__(self, check_item):
        self.check_item = check_item

    @staticmethod
    def login(user_id: str, password: str):
        data = {
            "user_id": user_id,
            "password": hashlib.md5(password.encode()).hexdigest(),
            "submit": ""
        }
        res = requests.post('https://acm.webturing.com/login.php', data=data)
        if "history.go(-2);" in res.text:
            return str(res.cookies)[37:63]

    @staticmethod
    def sign(cookies: str):
        '''返回获取的图灵币'''
        try:
            res = requests.get('https://acm.webturing.com/postFunction.php?action=sign', cookies={"PHPSESSID": cookies})
        except Exception:
            return None
        if "签到成功" in res.text:
            return re.findall(r" (\d+) 枚", res.text)[0] + "枚"
        else:
            return res.text.strip()

    @staticmethod
    def wallet(cookies: str):
        try:
            wallet_response = requests.get('https://acm.webturing.com/wallet.php',
                                           cookies={"PHPSESSID": cookies}
                                           ).text
        except Exception:
            return None
        try:
            wallet = BeautifulSoup(wallet_response, 'html.parser').find('strong').text
            if wallet is not None:
                wallet = wallet
            else:
                wallet = re.search(r"<strong>(\d+枚)</strong>", wallet_response).group()
                wallet = wallet.removeprefix("<strong>").removesuffix("</strong>")
            return wallet
        except Exception:
            return None

    @staticmethod
    def tag(cookies: str):
        def tgrj():
            url_tg = 'https://fabiaoqing.com/jichou/randomrj.html'
            b = requests.post(url_tg, headers=headers).json()
            data = {
                "textarea_Introduction": "舔狗日记\n" + " " * 47 + str(localtime(time()).tm_year) + '年' + b[
                    'today'] + " " * 47 + "\n    " + b['tgrj'],
                "user_id": '2701200522'
            }
            return data

        try:
            requests.post('https://acm.webturing.com/postFunction.php?action=editIntroduction',
                          cookies={"PHPSESSID": cookies}, data=tgrj())
        except Exception:
            return None

    def main(self):
        msg = {
            "账号姓名":"未知",
            "账号信息":"未知",
            "签到信息":"未知",
            "钱包信息":"未知"
        }
        username = self.check_item.get("username")
        password = self.check_item.get("password")
        name = self.check_item.get("name","未知")
        modtag = self.check_item.get("mod_tag", True)
        cookies = self.login(username, password)
        if cookies:
            sign_info = self.sign(cookies)
            wall_info = self.wallet(cookies)
            if sign_info:
                msg["签到信息"]=sign_info
            if wall_info:
                msg["钱包信息"]=wall_info
            if modtag:
                self.tag(cookies)
        else:
            msg.clear()
            msg["账号姓名"]=name
            msg['错误信息']="登录出错了"
        msg["账号信息"]=username
        msg["账号姓名"]=name
        msg='\n'.join([f"{i}: {msg[i]}" for i in msg])
        if "错误信息" in msg:
            print(f"{name} 签到失败")
        else:
            print(msg)
        return msg
